package com.xl.utils.http;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;

/**
 * @Author:XueH
 * @Description:
 * @Date:Created in 11:14 2023/12/27
 * @Modified By:
 */
@Slf4j
public class HttpActuator {

    private String ipAddr;

    private String port;

    private String path;

    private String http;

    private String https;
    //超时毫秒数
    private final Integer connectionTimeout;
    //毫秒
    private final Integer readTimeout;

    /**
     * 默认超时时间5s,最大超时时间10s
     *
     * @param ipAddr
     * @param port
     * @param path
     */
    public HttpActuator(String ipAddr, String port, String path) {
        createHttpActuator(ipAddr, port, path);
        this.connectionTimeout = 5000;
        this.readTimeout = 10000;
    }

    /**
     * 可以设置超时时间
     *
     * @param ipAddr
     * @param port
     * @param path
     * @param connectionTimeout 连接时间
     * @param readTimeout       读取时间
     */
    public HttpActuator(String ipAddr, String port, String path, Integer connectionTimeout, Integer readTimeout) {
        createHttpActuator(ipAddr, port, path);
        this.connectionTimeout = connectionTimeout;
        this.readTimeout = readTimeout;
    }

    private void createHttpActuator(String ipAddr, String port, String path) {
        this.ipAddr = ipAddr;
        this.port = port;
        if (StrUtil.isBlank(port)) {
            //网管默认nginx端口
            this.port = "80";
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        this.path = path;
        this.http = "http://" + this.ipAddr + ":" + this.port + this.path;
        this.https = "https://" + this.ipAddr + ":" + this.port + this.path;
    }

    public String getIpAddr() {
        return ipAddr;
    }

    public void setIpAddr(String ipAddr) {
        this.ipAddr = ipAddr;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getHttp() {
        return http;
    }

    public String getHttps() {
        return https;
    }

    public String getPath() {
        return path;
    }

    /**
     * 设置超时时间
     *
     * @param httpRequest
     */
    private void setTimeOut(HttpRequest httpRequest) {
        if (Objects.nonNull(connectionTimeout)) {
            httpRequest.setConnectionTimeout(connectionTimeout);
        }
        if (Objects.nonNull(readTimeout)) {
            httpRequest.setReadTimeout(readTimeout);
        }
    }


    /**
     * 无参 get请求
     *
     * @return
     */
    public String get() throws Exception {
        HttpRequest httpRequest = HttpRequest.get(http);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }


    /**
     * get通过参数map请求
     *
     * @param params
     * @return
     */
    public String get(Map<String, Object> params) throws Exception {
        HttpRequest httpRequest = HttpRequest.get(http).form(params);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }


    /**
     * 不带参数的POST请求
     *
     * @return
     * @throws Exception
     */
    public String post() throws Exception {
        HttpRequest httpRequest = HttpRequest.post(http);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }


    /**
     * 通过map请求
     *
     * @param params
     * @return
     */
    public String post(Map<String, Object> params) throws Exception {
        HttpRequest httpRequest = HttpRequest.post(http)
                .body(JSON.toJSONString(params));
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }


    /**
     * post form表单请求
     *
     * @param params
     * @return
     * @throws Exception
     */
    public String postForm(Map<String, Object> params) throws Exception {
        HttpRequest httpRequest = HttpRequest.post(http)
                .form(params);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }

    /**
     * post form表单请求 发送文件
     */
    public String postFormIncludeFile(Map<String, Object> params) throws Exception {
        HttpRequest httpRequest = HttpRequest.post(http).header("Content-Type", "multipart/form-data")
                .form(params);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }

    /**
     * 通过JSON请求
     *
     * @param jsonStr
     * @return
     */
    public String post(String jsonStr) throws Exception {
        HttpRequest httpRequest = HttpRequest.post(http)
                .body(jsonStr);
        setTimeOut(httpRequest);
        HttpResponse response = httpRequest
                .execute();
        return getResult(response);
    }


    /**
     * 通用结果获取
     *
     * @param response
     * @return
     * @throws Exception
     */
    private String getResult(HttpResponse response) throws Exception {
        if (HttpStatus.HTTP_OK == response.getStatus()) {
            String body = response.body();
            JSONObject parseObject = JSON.parseObject(body);
            if (Objects.nonNull(parseObject.get("code")) && parseObject.get("code").equals(HttpStatus.HTTP_OK)) {
                Object data = parseObject.get("data");
                if (Objects.isNull(data)) {
                    data = "";
                    log.info("http success! http:{}", http);
                } else {
                    log.info("http success! http:{} - response data:{}", http, data.toString());
                }
                return data.toString();
            } else {
                Object msg = parseObject.get("msg");
                log.error("http error! http:{} - msg data:{}", http, msg);
                throw new HttpException(msg.toString());
            }
        } else {
            log.error("http error! http:{} - response data:{}", http, JSON.toJSONString(response));
            throw new HttpException("请求失败");
        }
    }
}
